package com.leps.nq.common.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.leps.nq.common.exception.NqFileUploadException;
import com.leps.nq.config.NqConfig;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.UUID;

public class FileUploadUtils {

    private static String defaultUploadDir = NqConfig.getUploadDir();
    private static String avatarDir = NqConfig.getAvatarDir();

    public static void setDefaultUploadDir(String defaultUploadDir) {
        FileUploadUtils.defaultUploadDir = defaultUploadDir;
    }

    public static String getDefaultUploadDir() {
        return defaultUploadDir;
    }

    /**
     * 上传文件到默认的上传目录。
     * 默认上传目录配置方式：
     * <li>可通过application.yml进行配置：nq.uploadDir</li>
     * <li>可通过FileUploadUtil.setDefaultUploadDir()设置</li>
     * @param originalFile
     * @return
     * @throws IOException
     */
    public static String upload(MultipartFile originalFile) {
        return saveFile(originalFile, defaultUploadDir, false);
    }

    public static String uploadAvatar(MultipartFile originalFile) {
        return saveFile(originalFile, avatarDir, false);
    }

    private static String saveFile(MultipartFile originalFile, String saveDir, boolean useOriginFileName) {
        String saveFileName = genSaveFileName(originalFile, useOriginFileName);
        // ensure dir exists
        File dir = new File(saveDir);
        if(!dir.exists()) {
            dir.mkdirs();
        }
        // get absolute path
        String absPath = dir.getAbsolutePath() + File.separator + saveFileName;
        // save file
        try {
            originalFile.transferTo(Paths.get(absPath));
        } catch (IOException e) {
            throw new NqFileUploadException(e);
        }
        // return filename
        return saveFileName;
    }

    private static String genSaveFileName(MultipartFile originalFile, boolean useOriginFileName) {
        String originalFilename = originalFile.getOriginalFilename();
        String saveFileName = originalFilename;
        if(!useOriginFileName) {
            // generate a uuid style filename
            String suffix = FileUtil.getSuffix(originalFilename);
            saveFileName = UUID.randomUUID().toString();
            if (StrUtil.isNotEmpty(suffix))
                saveFileName = saveFileName + "." + suffix;
        }
        return saveFileName;
    }

    public static String uploadUseOriginFileName(MultipartFile originalFile) {
        return saveFile(originalFile, defaultUploadDir, true);
    }


}
